<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      list-style: none;
    }

    ul li {
      width: 100%;
      height: 20px;
      margin-bottom: 5px;
      background-color: grey;
    }

    li.active {
      background-color: yellow;
    }

    .box {
      width: 200px;
      height: 200px;
      border: 1px solid red;
      display: table;
    }

    .sub {
      width: 20px;
      height: 20px;
      background: red;
      margin: auto;
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="sub"></div>
  </div>
  <ul>
    <li class="active"></li>
    <li></li>
    <li></li>
  </ul>
  <script>
    window.onload = function () {
      let list = document.querySelectorAll('li')
      // 记录移动前选中li的对应索引
      let preActiveIndex = 0
      for (let i = 0; i < list.length; i++) {
        // (function (j) {
        const li = list[i]
        // console.log({ i, j });
        li.onmouseover = function () {
          // 清除
          list[preActiveIndex].className = ''
          // 设置
          this.className = 'active'
          // 赋值
          preActiveIndex = i
        }
        // })(i)
      }
    }
    // 常规写法
    // window.onload = function() {
    //   let list = document.querySelectorAll('li')
    //   for (let i = 0; i < list.length; i++) {
    //     const li = list[i]
    //     li.onmouseover = function() {
    //       for (let j = 0; j < list.length; j++) {
    //         list[j].className = ''
    //       }
    //       this.className = 'active'
    //     }
    //   }
    // }
  </script>
</body>

</html>